<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="排产状态" prop="wplanStatus">
        <el-select v-model="queryParams.wplanStatus" placeholder="请选择" clearable>
          <el-option
            v-for="dict in planStatusList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产地" prop="factoryId">
        <el-select v-model="queryParams.factoryId" placeholder="请选择" filterable clearable @change="factoryChange">
          <el-option v-for="team in factoryList" :key="team.deptId" :label="team.deptName" :value="team.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="班组" prop="teamId">
        <el-select v-model="queryParams.teamId" placeholder="请选择" clearable>
          <el-option v-for="team in teamList" :key="team.deptId" :label="team.deptName" :value="team.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单合同号" prop="contractCode">
        <el-input v-model="queryParams.contractCode" placeholder="请输入订单合同号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品编码" prop="bomCode">
        <el-input
          v-model="queryParams.bomCode"
          placeholder="请输入产品编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="bomName">
        <el-input
          v-model="queryParams.bomName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="teamSelect"
          @click="handlePlan('MULITPLE', {})"
          v-hasPermi="['factory:factorywplan:edit']"
        >执行排产（当前选择)</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="teamSelect"
          @click="handlePlanOfAll('ALL')"
          v-hasPermi="['factory:factorywplan:edit']"
        >执行排产（符合条件）</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading"
              border style="width:100%;" ref="multipleTable" :data="factoryWorkOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"  :selectable="handleDisable"/>
      <el-table-column label="班组名称" align="center" prop="teamName" />
      <el-table-column label="合同编号" align="center" prop="contractCode" />
      <el-table-column label="产品编码" align="center" prop="bomCode" />
      <el-table-column label="产品名称" align="center" prop="bomName" />
      <el-table-column label="规格型号" align="center" prop="productStandard" />
      <el-table-column label="产品单位" align="center" prop="productUnit"  width="80px"/>
      <el-table-column label="产品数量" align="center" prop="workerOrdernum"  width="80px"/>
      <el-table-column label="采样数量" align="center" prop="sampleNum" />
      <el-table-column label="排产数量" align="center" prop="planNum" width="80px"/>
      <el-table-column label="总部开始时间" align="center" prop="planStartdate" width="100"/>
      <el-table-column label="总部完成时间" align="center" prop="planFinishdate" width="100"/>
      <el-table-column label="排产开始日期" align="center" prop="wplanStartDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.wplanStartDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排产完成时间" align="center" prop="wplanEndDate" width="100"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.storeStatus == '0'"
            @click="handlePlan('SINGLE', scope.row)"
            v-hasPermi="['factory:factorywplan:edit']"
          >执行排产</el-button>
          <!--<el-button size="mini" type="text" icon="el-icon-edit" v-if="scope.row.wplanStatus == '1'"
            @click="handlePrint(scope.row)" v-hasPermi="['factory:factorywplan:edit']">打印工单</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单信息对话框 -->
    <el-dialog title="分厂周排产" :visible.sync="open" width="1650px" :close-on-click-modal ="false" append-to-body>
      <!-- 数据统计 -->
      <div style="clear: both;margin-bottom: 30px;">
        <el-row :gutter="26">
          <el-col :span="3">
            <div>
              <el-statistic title="所选班组">
                <template slot="formatter">{{ teamName }}</template>
              </el-statistic>
            </div>
          </el-col>
          <el-col :span="3">
            <div>
              <el-statistic title="已选数量">
                <template slot="formatter">{{selectedCount}}条</template>
              </el-statistic>
            </div>
          </el-col>
          <el-col :span="3">
            <div>
              <el-statistic group-separator="," :precision="2" :value="standardCapacity" title="标准产能/天"/>
            </div>
          </el-col>
          <el-col :span="3">
            <div>
              <el-statistic group-separator="," :precision="2" :value="totalStandardCapacity" title="总标准产能" />
            </div>
          </el-col>
          <el-col :span="3">
            <div>
              <el-statistic group-separator="," :precision="2" :value="restCapacity" title="总剩余产能"/>
            </div>
          </el-col>
          <el-col :span="3">
            <div>
              <el-statistic group-separator="," :precision="2" :value="needCapacity" title="所需产能"/>
            </div>
          </el-col>
        </el-row>
      </div>
      <div style="float: right; clear: both;">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px"  style="margin-bottom: 10px">
          <el-date-picker clearable
            v-model="form.weekStartDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择开始日期">
          </el-date-picker>
          -
          <el-date-picker clearable
            v-model="form.weekEndDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择开始日期">
          </el-date-picker>
          <!--<el-button type="primary" @click="printPlan" style="margin-left: 20px;">打印周计划</el-button>-->
          <el-button type="primary" @click="excutePlan" style="margin-left: 20px;">排产计算</el-button>
        </el-form>
      </div>
      <template v-for="planItem in wplanProductVOList">
        <div style="margin-right: 5px;margin-top: 10px;">
          <el-tag :type="planItem.typeTag" size="medium"  effect="light" style="margin-right: 25px;">
            合同号：{{planItem.contractCode}}
          </el-tag>
          <el-checkbox v-model="planItem.labelCheckAll" @change="labelCheckAllChange(planItem)">标签文档全选</el-checkbox>
          <el-checkbox v-model="planItem.packageCheckAll" @change="packageCheckAllChange(planItem)">包装单全选</el-checkbox>
          <el-checkbox v-model="planItem.bothOfCheckAll" @change="bothOfCheckAllChange(planItem)">两者同时全选</el-checkbox>
        </div>
        <el-table
          style="width: 100%"
          row-key="id"
          border
          lazy
          v-loading="loading2"
          :load="load"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          :data="planItem.wplanList" >
          <el-table-column label="子项物料编码" align="center" prop="bomCode"  width="160px" />
          <el-table-column label="物料名称" align="center" prop="bomName" />
          <el-table-column label="规格型号" align="center" prop="bomStandard" />
          <el-table-column label="订单合同号" align="center" prop="contractCode" />
          <el-table-column label="下单日期" align="center" prop="orderDate" />
          <el-table-column label="订单数量" align="center" prop="orderNum" />
          <el-table-column label="库存" align="center" prop="storeNum" width="90px"/>
          <el-table-column label="已完成数量" align="center" prop="finishNum" />
          <el-table-column label="标签文档" align="center" class-name="small-padding fixed-width" prop="labelCheck" width="60px">
            <template slot-scope="scope">
              <el-checkbox v-if="scope.row.levelValue===1" v-model="scope.row.labelCheck"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="包装单" align="center" class-name="small-padding fixed-width" prop="packageCheck" width="60px">
            <template slot-scope="scope">
              <el-checkbox v-if="scope.row.levelValue===1" v-model="scope.row.packageCheck"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="待排产数量" align="center" prop="planNum" width="90px"/>
          <el-table-column label="排产数量" align="center" prop="planCapacity"  width="110px">
            <template slot-scope="scope">
              <el-tag type="success" v-if="scope.row.planCapacity!=null">{{scope.row.planCapacity}} {{scope.row.bomUnit == null ? '' : scope.row.bomUnit}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="排产情况" align="center" prop="capacityDesc" width="100px"/>
          <el-table-column label="计划开始" align="center" prop="wplanStartDate"  width="100px"/>
          <el-table-column label="计划完成" align="center" prop="wplanEndDate"  width="100px" >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.wplanEndDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="总部开始" align="center" prop="planStartdate" width="100px"/>
          <el-table-column label="总部完成" align="center" prop="planFinishdate" width="100px"/>
          <el-table-column label="剩余数量" align="center" prop="nextNum" />

          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="60px" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                v-if="scope.row.capacityDesc!=null"
                @click="handleAdjust(scope.row)"
                v-hasPermi="['factory:factorymplan:edit']"
              >调整</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                v-if="scope.row.levelValue===1"
                @click="handPlanRemoveOrder(scope.row)"
                v-hasPermi="['factory:factorymplan:edit']"
              >移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button type="primary" @click="submitPlan" >提交排产</el-button>
      </div>
    </el-dialog>
    <!-- 排产调整对话框 -->
    <el-dialog
      title="排产调整"
      :visible.sync="adjustopen"
      width="800px"
      append-to-body
    >
       <div style="margin-bottom: 20px;text-align: center;">
         <el-row :gutter="16">
           <el-col :span="4" style="margin-right: 100px;">
             <div>
               计划开始日期：
               <el-date-picker
                 clearable
                 v-model="adjustWplanSelected.wplanStartDate"
                 type="date"
                 value-format="yyyy-MM-dd"
                 placeholder="计划开始日期"
                 @change="wplanDateChange"
               >
               </el-date-picker>
             </div>
           </el-col>
           <el-col :span="4">
             <div>
               计划结束日期：
               <el-date-picker
                 clearable
                 v-model="adjustWplanSelected.wplanEndDate"
                 type="date"
                 value-format="yyyy-MM-dd"
                 placeholder="计划结束日期"
                 @change="wplanDateChange"
               >
               </el-date-picker>
             </div>
           </el-col>
         </el-row>
       </div>
      <el-table v-loading="loading" :data="adjustWplanSelected.wplanDetailList">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column label="排产日期" align="center" prop="planDate" width="300">
          <template slot-scope="scope">
            <el-date-picker
              clearable
              v-model="scope.row.planDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择开始时间"
            >
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="排产数量" align="center" prop="planCapacity" width="200px">
          <template slot-scope="scope">
            <el-input v-model="scope.row.planCapacity" placeholder="排产数量" clearable ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              v-if="scope.$index>0"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="wplanDateRemove(scope.row)"
              v-hasPermi="['factory:factorywplan:edit']"
            >移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAdjustForm">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listWFactoryWorkorder,listWplanWorkorder,listChooseWplanWorkorder,listChooseWplanWorkorderOfAll } from "@/api/sm/order/workorder";
import { listFactorywplan, excuteFactoryWPlan,submitFactoryWPlan,printPlan} from "@/api/sm/factory/factorywplan";
import { listTeam,listFactory } from "@/api/system/dept";
import { listChildren } from "@/api/sm/basic/bominfo";

export default {
  name: "Orderinfo",
  dicts: ['order_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      loading2: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      teamSelect: true,
      planCal: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      plantotal: 0,
      //分厂待排产订单信息表格数据
      factoryWorkOrderList: [],
      factoryList: [],
      teamList: [],
      adjustWplanSelected: {},
      // 废弃
      adjustWplanDetailList: [],
      //排产工单
      wplanProductVOList: [],
      //排产结果
      planResultList: [],
      planStatusList: [
        {
          "label": "待排产",
          "value": 0
        },
        {
          "label": "排产完成",
          "value": 1
        }
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      adjustopen: false,
      // 同步时间时间范围
      daterangeOrderDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bomCode: null,
        bomName: null,
        teamId: null,
        workerConfirmstatus: 1,
        planStatus: 1,
        wplanStatus: 0,
        wplanStatuss: "0,2",
        workerOrdertype: 1,
        excludeIds: [],
      },
      // 表单参数
      form: {
        teamId: null,
        weekStartDate: null,
        weekEndDate: null,
        workOrderIds: null
      },
      // 表单参数
      form1: {
        wplanList: null
      },
      form2: {
        mId: null,
        wplanStartDate: null,
        wplanEndDate: null
      },
      // 表单校验
      rules: {
      },
      // 统计数据
      teamName: "-",
      selectedCount: 0,
      standardCapacity: 0,
      totalStandardCapacity: 0,
      restCapacity: 0,
      needCapacity: 0,
      action: null,
    };
  },
  created() {
    this.getList();
    this.getFactoryList();
    //this.getTeamList();
    //this.getThisSaturday();
    //this.getNextSaturday();
  },
  methods: {
    formatDateToYYYYMMDD(date) {
      const year = date.getFullYear();
      let month = date.getMonth() + 1; // 月份是从 0 开始的，需要加 1
      let day = date.getDate();

      // 如果月份或日期小于 10，前面补零
      if (month < 10) {
        month = '0' + month;
      }
      if (day < 10) {
        day = '0' + day;
      }
      return `${year}-${month}-${day}`;
    },
    wplanDateRemove(row) {
      let wplanList = this.adjustWplanSelected.wplanDetailList;
      if (wplanList.length === 0) {
        alert('已经无日期删除');
      }
      for(let i=0;i<wplanList.length;i++) {
        let obj = wplanList[i];
        if (obj.planDate === row.planDate) {
          wplanList.splice(i, 1);
          break;
        }
      }
    },
    wplanDateChange() {
      let wplanDetailList = this.adjustWplanSelected.wplanDetailList;
      if (wplanDetailList.length === 0) {
        alert('已经无日期调整');
      }
      let cloneSrcObject = this.adjustWplanSelected.wplanDetailList[0];

      const newStart = new Date(this.adjustWplanSelected.wplanStartDate);
      const newEnd = new Date(this.adjustWplanSelected.wplanEndDate);

      let preStart = new Date(this.adjustWplanSelected.wplanDetailList[0].planDate);
      let preEnd = new Date(this.adjustWplanSelected.wplanDetailList[this.adjustWplanSelected.wplanDetailList.length-1].planDate);

      // 调整结束日期，循环变量从起始日期开始，逐天增加
      while (newEnd > preEnd) {
        preEnd.setDate(preEnd.getDate() +1);
        let curPlanDate = this.formatDateToYYYYMMDD(preEnd);
        const exists = this.adjustWplanSelected.wplanDetailList.some(item => item.planDate === curPlanDate);
        if (!exists) {
          let rowWPlan = {};
          Object.assign(rowWPlan, cloneSrcObject);
          rowWPlan.planCapacity = 0;
          rowWPlan.planDate = curPlanDate;
          this.adjustWplanSelected.wplanDetailList.push(rowWPlan);
        }
      }

      // 调整开始日期
      while (newStart < preStart) {
        preStart.setDate(preStart.getDate() -1);
        let curPlanDate = this.formatDateToYYYYMMDD(preStart);
        const exists = this.adjustWplanSelected.wplanDetailList.some(item => item.planDate === curPlanDate);
        if (!exists) {
          let rowWPlan = {};
          Object.assign(rowWPlan, cloneSrcObject);
          rowWPlan.planCapacity = 0;
          rowWPlan.planDate = curPlanDate;
          this.adjustWplanSelected.wplanDetailList.unshift(rowWPlan);
        }
      }
    },
    labelCheckAllChange(planItem) {
      let wplanList = planItem.wplanList || [];
      for(let wplan of wplanList) {
        wplan.labelCheck = planItem.labelCheckAll;
      }
      planItem.bothOfCheckAll = planItem.labelCheckAll && planItem.packageCheckAll;
    },
    packageCheckAllChange(planItem) {
      let wplanList = planItem.wplanList || [];
      for(let wplan of wplanList) {
        wplan.packageCheck = planItem.packageCheckAll;
      }
      planItem.bothOfCheckAll = planItem.labelCheckAll && planItem.packageCheckAll;
    },
    bothOfCheckAllChange(planItem) {
      let wplanList = planItem.wplanList || [];
      for(let wplan of wplanList) {
        wplan.labelCheck = planItem.bothOfCheckAll;
        wplan.packageCheck = planItem.bothOfCheckAll;
      }
      planItem.labelCheckAll = planItem.bothOfCheckAll;
      planItem.packageCheckAll = planItem.bothOfCheckAll;
    },

    /** 调整排产日期功能 提交按钮 */
    submitAdjustForm() {

      if(this.form2.wplanEndDate<this.form2.wplanStartDate){
        alert("完成时间不能小于开始时间");
        return;
      }

      this.adjustopen = false;
      // for(let plan of this.wplanProductVOList) {
      //   for(let planItem of plan.wplanList) {
      //     if (planItem.id === this.form2.mId) {
      //       // temFind = planItem;
      //       Object.assign(planItem, this.form2);
      //       break;
      //     }
      //   }
      // }
    },
    cancel2() {
      this.adjustopen = false;
      this.reset2();
    },
    reset2(){
      this.form2 = {
        mId: null,
        wplanStartDate: null,
        wplanEndDate: null
      };
      this.resetForm("form2");
    },
    handleAdjust(row) {
      this.reset2();
      this.adjustWplanSelected = row;
      this.adjustopen = true;
      //console.log(JSON.stringify(row));
      // this.adjustWplanDetailList = row.wplanDetailList;
      //this.form2.mId = row.id;
     // this.form2.wplanStartDate = row.wplanStartDate;
      //this.form2.wplanEndDate = row.wplanEndDate;
    },
    load(tree, treeNode, resolve) {
      console.log(tree);
      let data = {
        "parentBomCode": tree.bomCode,
        "productId": tree.productId,
        "orderCode": tree.orderCode,
        "customName": tree.customName,
        "sampleNum": tree.sampleNum ? tree.sampleNum : 0,
        "workerOrdernum": tree.workerOrdernum ? tree.workerOrdernum : 0,
        // "semiProductPlanNum": tree.semiProductPlanNum ? tree.semiProductPlanNum : tree.planNum
      };
      listChildren(data).then((res) => {   //getChildMenu是我们自己的调用后台的封装
        resolve(                            //resolve是组件的
          res.data  //根据自己的格式,将查到的子菜单数组填充
        )
      })
    },

    //打印周计划
    printPlan() {
      if(this.planCal==false){
        alert("请先排产,再打印周计划");
        return;
      }

      this.form1.wplanList=[];
      for(let obj of this.wplanProductVOList) {
        for(let cur of obj.wplanList) {
          this.form1.wplanList.push(cur);
        }
      }

      printPlan(this.form1).then(response => {
        let blob = new Blob([response], { type: "application/vnd.ms-excel" });
        var downloadElement = document.createElement("a");

        var href = window.URL.createObjectURL(blob); //创建下载的链接

        downloadElement.href = href;

        downloadElement.download = '周排产_工单'; //下载后文件名

        document.body.appendChild(downloadElement);

        downloadElement.click(); //点击下载

        document.body.removeChild(downloadElement); //下载完成移除元素

        window.URL.revokeObjectURL(href); //释放掉blob对象

        this.loading = false;
      });
    },

    getFactoryList() {
      this.loading = true;
      listFactory({"level":2}).then(response => {
        this.factoryList = response.data;
        this.queryParams.factoryId = this.factoryList[0].deptId;
        this.getTeamList(this.queryParams.factoryId);
        this.loading = false;
      });
    },
    factoryChange(){
      this.getTeamList(this.queryParams.factoryId);
    },
    /** 查询订单信息列表 */
    getTeamList(parentId) {
      this.loading = true;
      listTeam({"parentId":parentId}).then(response => {
        this.teamList = response.data;
        this.loading = false;
      });
    },

    handlePrint(row) {
      this.loading = true;
      const ids = row.id || this.ids;
      printWplanWorkOrder(ids).then(response => {
        let blob = new Blob([response], { type: "application/vnd.ms-excel" });
        var downloadElement = document.createElement("a");

        var href = window.URL.createObjectURL(blob); //创建下载的链接

        downloadElement.href = href;

        downloadElement.download = '月排产_工单'; //下载后文件名

        document.body.appendChild(downloadElement);

        downloadElement.click(); //点击下载

        document.body.removeChild(downloadElement); //下载完成移除元素

        window.URL.revokeObjectURL(href); //释放掉blob对象

        this.loading = false;
      });
    },
    getThisSaturday() {
      var currentDate = new Date();
      var currentDay = currentDate.getDay(); // 获取当前是星期几（0-6，0代表星期日）
      var daysUntilFriday = 6 - currentDay;
      currentDate.setDate(currentDate.getDate() + daysUntilFriday);
      return this.form.weekStartDate=currentDate;
    },
    getNextSaturday() {
      var currentDate = new Date();
      var currentDay = currentDate.getDay(); // 获取当前是星期几（0-6，0代表星期日）
      var daysUntilFriday = 13 - (currentDay+1);
      currentDate.setDate(currentDate.getDate() + daysUntilFriday);
      return this.form.weekEndDate=currentDate;
    },
    handleDisable(row, index) {
      if (row.wplanStatus == '1') {
        return false
      } else {
        return true
      }
    },
    /** 查询订单信息列表 */
    getList() {
      this.loading = true;
      listWFactoryWorkorder(this.queryParams).then(response => {
        this.factoryWorkOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        weekStartDate: null,
        weekEndDate: null,
        workOrderIds: null
      };
      this.resetForm("form");
    },
    reset1() {
      this.form1 = {
        wplanList: null
      };
      this.resetForm("form1");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.excludeIds = [];
      this.queryParams.pageNum = 1;
      if(this.queryParams.teamId!=null && this.queryParams.teamId!=undefined){
        this.teamSelect = false;
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeOrderDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
     /** 执行排产操作 */
    handlePlan(action, row) {
      this.action = action;
      this.reset();
      this.reset1();
      this.getThisSaturday();
      this.getNextSaturday();
      this.loading2 = true;
      const ids = row.id || this.ids;
      this.orderplanList = null;
      this.wplanProductVOList = [];
      listChooseWplanWorkorder({"ids":ids+'',"teamId":this.queryParams.teamId,"planStartdate":this.form.weekStartDate+'',"planFinishdate":this.form.weekEndDate+''}).then(response => {
        this.wplanProductVOList = response.data.wplanProductVOList || [];

        this.open = true;
        //this.title = "待排产工单";
        this.planCal = false;
        this.loading2 = false;
        this.teamName = response.data.teamName;
        this.selectedCount = this.wplanProductVOList.length;
        this.standardCapacity = new Number(response.data.standardCapacity);
        this.totalStandardCapacity = new Number(response.data.totalStandardCapacity);
        this.restCapacity = new Number(response.data.nextCapacity);
        this.needCapacity = new Number(response.data.needCapacity);
      });
    },
    handlePlanOfAll(action) {
      this.action = action;
      if (this.action === 'ALL') {
        this.queryParams.excludeIds = [];
      }
      this.reset1();
      this.loading2 = true;
      this.orderplanList = null;
      this.wplanProductVOList = [];
      listChooseWplanWorkorderOfAll(this.queryParams).then(response => {
        this.wplanProductVOList = response.data.wplanProductVOList || [];

        this.open = true;
        //this.title = "待排产工单";
        this.planCal = false;
        this.loading2 = false;
        this.teamName = response.data.teamName;
        this.selectedCount = this.wplanProductVOList.length;
        this.standardCapacity = new Number(response.data.standardCapacity);
        this.totalStandardCapacity = new Number(response.data.totalStandardCapacity);
        this.restCapacity = new Number(response.data.workOrderNum);
        this.needCapacity = new Number(response.data.needCapacity);
      });
    },

    handPlanRemoveOrder(row) {
      const id = row.id
      for(let i =0; i<this.wplanProductVOList.length; i++) {
        let obj = this.wplanProductVOList[i];
        obj.wplanList.map((item, index) => {
          if (item.id === id) {
            obj.wplanList.splice(index, 1);
            this.queryParams.excludeIds.push(id);
          }
        });
        // 判断一个半成品也没有了
        if (obj.wplanList.length === 0) {
          this.wplanProductVOList.splice(i, 1);
        }
      }
      if (this.wplanProductVOList.length === 0) {
        this.$modal.msgSuccess("仅有一个产品都被删除了，分厂周排产窗口被关闭");
        this.open = false;
        this.queryParams.excludeIds = [];
        return;
      }
      // 只有多选才会删除表中数据
      if (this.action === 'MULTIPLE') {
        // 重新计算开始
        for (let i = 0; i < this.factoryWorkOrderList.length; i++) {
          let cur = this.factoryWorkOrderList[i];
          if (cur.id === row.id) {
            this.$refs.multipleTable.toggleRowSelection(this.factoryWorkOrderList[i], false);
            break;
          }
        }
        // 计算后的数据，如果存在也要移除
        for (let i = 0; i < this.ids.length; i++) {
          if (this.ids[i] === id) {
            this.ids.splice(i, 1);
            break;
          }
        }
        // 重新做排产计算
        this.handlePlan(this.action,{});
      } else {
        this.handlePlanOfAll('ALL_DELETE');
      }
    },

    excutePlan() {
      if(this.wplanProductVOList.length==0){
        alert("无排产工单");
        return;
      }
      let planWorkOrderList = [];
      for(let obj of this.wplanProductVOList) {
        for(let cur of obj.wplanList) {
          planWorkOrderList.push(cur);
        }
      }
      this.loading2 = true;
      this.form.teamId = this.queryParams.teamId;
      this.form.workOrderIds = planWorkOrderList.map(item => item.id).join(',')
      excuteFactoryWPlan(this.form).then(response => {
        this.wplanProductVOList = response.data.wplanProductVOList || [];
        this.$modal.msgSuccess("排产成功");
        this.teamName = response.data.teamName;
        this.selectedCount = this.wplanProductVOList.length;
        this.standardCapacity = new Number(response.data.standardCapacity);
        this.totalStandardCapacity = new Number(response.data.totalStandardCapacity);
        this.restCapacity = new Number(response.data.nextCapacity);
        this.needCapacity = new Number(response.data.needCapacity);
        this.planCal = true;
        this.loading2 = false;
      });
    },

    submitPlan() {
      if(this.planCal==false){
        alert("请先周排产,再提交");
        return;
      }
      this.$modal.confirm('确认周计划已经打印好，现在提交周计划?').then(() => {
        this.form1.wplanList=[];
        for(let obj of this.wplanProductVOList) {
          for(let cur of obj.wplanList) {
            this.form1.wplanList.push(cur);
          }
        }
        submitFactoryWPlan(this.form1).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.open = false;
          this.getList();
        });
      }).then(() => {

      }).catch(() => {

      });

    },
  }
};
</script>
